package vn.hanelsoft.openwifi.control;

import org.json.JSONObject;

import vn.hanelsoft.openwifi.R;
import vn.hanelsoft.openwifi.model.delegate.ServerDelegate;
import vn.hanelsoft.openwifi.model.object.ObjectFacebook;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;

public class FacebookAccountActivity extends Activity implements
		OnClickListener {

	Context mContext;

	EditText edFacebookId, edPassword;
	LinearLayout lnLogin;

	// for facebook
	String access_token;
	Session.StatusCallback statusCallback = new SessionStatusCallback();
	Bundle mSavedInstanceState;
	Session mSession;
	ObjectFacebook mObjectFacebook;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_facebook_account);
		mSavedInstanceState = savedInstanceState;
		initDB();
		initView();
		loginToFacebook();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.lnLogin:

			break;

		default:
			break;
		}

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		activityFinish();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mSession = Session.getActiveSession();
		Session.saveSession(mSession, outState);
	}
	

//	@Override
//	protected void onStop() {
//		super.onStop();
//		UtilsCommon.disConnectWifi(mContext);
//	}
	/*------------------- Custom Function ------------------------*/

	void initDB() {
		mContext = this;
	}

	void initView() {
		edFacebookId = (EditText) findViewById(R.id.edFacebookId);
		edPassword = (EditText) findViewById(R.id.edPassword);
		lnLogin = (LinearLayout) findViewById(R.id.lnLogin);
	}

	void activityFinish() {
		finish();
		overridePendingTransition(
				R.drawable.activity_transaction_trans_right_in,
				R.drawable.activity_transaction_trans_right_out);
	}

	private void loginToFacebook() {
		try {
			Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
			Session session = Session.getActiveSession();
			if (session == null) {
				if (mSavedInstanceState != null) {
					session = Session.restoreSession(this, null,
							statusCallback, mSavedInstanceState);
				}
				if (session == null) {
					session = new Session(this);
				}
//				session.openForPublish(requestPermission());
				Session.openActiveSession(FacebookAccountActivity.this, true, statusCallback);
			}
			updateViewFacebook();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			updateViewFacebook();
		}
	}

	// request Permissions
	Session.OpenRequest requestPermission() {
		Session.OpenRequest requestPermissions = new Session.OpenRequest(FacebookAccountActivity.this);
		requestPermissions.setPermissions("");
		requestPermissions.setCallback(statusCallback);
		requestPermissions.setRequestCode(100);
		return requestPermissions;
	}
	
	private void updateViewFacebook() {
		try {
			Session session = Session.getActiveSession();
			if (session.isOpened()) {
				if (access_token == null) {
					access_token = session.getAccessToken();
					ServerDelegate.getFacebookProfile(mhandler, access_token);
					
				}
			} else {
				if (!session.isOpened() && !session.isClosed()) {
					session.openForPublish(requestPermission());
				} else {
					Session.openActiveSession(FacebookAccountActivity.this, true, statusCallback);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {

					mObjectFacebook = new ObjectFacebook();
					
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					try {
						mObjectFacebook.setFacebookId(dataJSONObject.getString("id"));
						mObjectFacebook.setName(dataJSONObject.getString("name"));
						mObjectFacebook.setSrcImage("http://graph.facebook.com/"+mObjectFacebook.getFacebookId()+"/picture?type=small");
						Log.d("Luong", "-------------------------mObjectFacebook Name: "+mObjectFacebook.getName());
					} catch (Exception e) {
						// TODO: handle exception
					}

				} catch (Exception e) {
					
				}
			} else {
				
			}
		}
	};
	
}
